package com.ftg.wymall.config;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 *
 * GatewayFilter 过滤器
 * 1 ： 拦截所有请求
 * 2 : 判断所有请求是否满足匹配条件
 * 3 : 可以走相应的路由
 * 4 ： 可以进行相应的处理
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/11/11 上午10:15
 */
@Component
public class CorsFilterConfig implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 过滤并返回经过过滤器链处理的响应
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 将"*"添加到响应头的"Access-Control-Allow-Origin"中
            exchange.getResponse().getHeaders().add("Access-Control-Allow-Origin", "*");
            // 将"POST, GET, OPTIONS, DELETE"添加到响应头的"Access-Control-Allow-Methods"中
            exchange.getResponse().getHeaders().add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            // 将"3600"添加到响应头的"Access-Control-Max-Age"中
            exchange.getResponse().getHeaders().add("Access-Control-Max-Age", "3600");
        }));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}